
from django.http import HttpResponse
from django.template import RequestContext
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.core.urlresolvers import reverse
from models import *
from forms import *
from utils import PEDIDO_SESSION_KEY
from decorators import pedido_required



def cadastro(request):
    if request.user.is_authenticated():
        return redirect(reverse('index'))
    
    elif request.method == 'GET':
        usuario_form = RegistroUsuarioForm(prefix='usuario')
        endereco_form = RegistroEnderecoForm(prefix='endereco')
        telefone_form = RegistroTelefoneForm(prefix='telefone')
        
    else:
        data = request.POST.copy()
        usuario_form = RegistroUsuarioForm(data, prefix='usuario')
        endereco_form = RegistroEnderecoForm(data, prefix='endereco')
        telefone_form = RegistroTelefoneForm(data, prefix='telefone')
        
        if usuario_form.is_valid():
            usuario = usuario_form.save()
            endereco_form = RegistroEnderecoForm(data, prefix='endereco')
            telefone_form = RegistroTelefoneForm(data, prefix='telefone')
            
            if endereco_form.is_valid() and telefone_form.is_valid():
                endereco = endereco_form.save(commit=False)
                telefone = telefone_form.save(commit=False)
                usuario.save()
                endereco.usuario = usuario
                telefone.usuario = usuario
                endereco.save()
                telefone.save()
                
                usuario = authenticate(username=data['usuario-username'], 
                    password=data['usuario-password1'])
                login(request, usuario)
                
                return redirect(reverse('index'))
            else:
                usuario.delete()
        
    return render_to_response('cadastro.html',
        {'usuario_form': usuario_form, 'endereco_form': endereco_form, 
         'telefone_form': telefone_form},
        context_instance=RequestContext(request))


@login_required
def index(request):
    home = 'voce esta na home do site'
    return render_to_response('index.html', {'home' : home},
        context_instance=RequestContext(request))


@login_required
def relatorio(request):
    if not request.user.is_staff:
        return redirect(reverse('index'))
        
    def cmp2(x,y):
        return cmp(x[1], y[1])
    
    bairros = sorted([(b.nome, User.objects.filter(endereco__bairro=b).distinct()
        .count()) for b in Bairro.objects.all()], cmp=cmp2, reverse=True)
    
    sabores = sorted([(p.nome, p.pizzapedida_set.all().count()) 
        for p in Pizza.objects.all()], cmp=cmp2, reverse=True)
    
    return render_to_response('relatorio.html', {'bairros': bairros,
        'sabores': sabores},
        context_instance=RequestContext(request))


################################################################################

@login_required
def fazer_pedido(request):
    if PEDIDO_SESSION_KEY not in request.session:
        pedido = Pedido.objects.create(usuario=request.user, status=Pedido.EM_ABERTO)
        request.session[PEDIDO_SESSION_KEY] = pedido
    else:
        pedido = request.session[PEDIDO_SESSION_KEY]
    
    return render_to_response('pedido.html', {'pedido': pedido}, 
	    context_instance=RequestContext(request))


@login_required
@pedido_required
def adicionar_item(request):
    if request.method == 'GET':
        item_form = ItemPedidoForm()
    else:
        item_form = ItemPedidoForm(request.POST)
        if item_form.is_valid():
            pedido = request.session[PEDIDO_SESSION_KEY]
            item = item_form.save(commit=False)
            item.pedido = pedido
            item.save()
            return redirect(reverse('fazer_pedido'))
            
    return render_to_response('adicionar_item.html',
        {'form': item_form, 'novo': True},
	    context_instance=RequestContext(request))


@login_required
@pedido_required
def editar_item(request, pk):
    item = get_object_or_404(ItemPedido, pk=pk)
    if request.method == 'GET':
        item_form = ItemPedidoForm(instance=item)
    else:
        item_form = ItemPedidoForm(request.POST, instance=item)
        if item_form.is_valid():
            item_form.save()
            return redirect(reverse('fazer_pedido'))
        
    return render_to_response('adicionar_item.html', {'form': item_form}, 
	    context_instance=RequestContext(request))


@login_required
@pedido_required
def remover_item(request, pk):
    item = get_object_or_404(ItemPedido, pk=pk)
    item.delete()
    return redirect(reverse('fazer_pedido'))


@login_required
@pedido_required
def adicionar_pizza(request):
    if request.method == 'GET':
        pizza_form = PizzaPedidaForm()
    else:
        pizza_form = PizzaPedidaForm(request.POST)
        if pizza_form.is_valid():
            pedido = request.session[PEDIDO_SESSION_KEY]
            pizza = pizza_form.save(commit=False)
            pizza.pedido = pedido
            pizza.save()
            pizza_form.save_m2m()
            return redirect(reverse('fazer_pedido'))
            
    return render_to_response('adicionar_pizza.html',
        {'form': pizza_form, 'novo': True},
	    context_instance=RequestContext(request))


@login_required
@pedido_required
def editar_pizza(request, pk):
    pizza = get_object_or_404(PizzaPedida, pk=pk)
    if request.method == 'GET':
        pizza_form = PizzaPedidaForm(instance=pizza)
    else:
        pizza_form = PizzaPedidaForm(request.POST, instance=pizza)
        if pizza_form.is_valid():
            pizza_form.save()
            return redirect(reverse('fazer_pedido'))
        
    return render_to_response('adicionar_pizza.html', {'form': pizza_form}, 
	    context_instance=RequestContext(request))


@login_required
@pedido_required
def remover_pizza(request, pk):
    pizza = get_object_or_404(PizzaPedida, pk=pk)
    pizza.delete()
    return redirect(reverse('fazer_pedido'))
    

@login_required
@pedido_required
def confirmar_pedido(request):
    pedido = request.session[PEDIDO_SESSION_KEY]
    
    if request.method == 'GET':
        pedido_form = ConfirmarPedidoForm(instance=pedido)
    else:
        pedido_form = ConfirmarPedidoForm(request.POST, instance=pedido)
        if pedido_form.is_valid():
            pedido = pedido_form.save(commit=False)
            pedido.status = Pedido.EM_PREPARACAO
            pedido.save()
            del request.session[PEDIDO_SESSION_KEY]
            return redirect(reverse('acompanhar_pedido'))
            
    enderecos = Endereco.objects.filter(usuario=pedido.usuario)
    telefones = Telefone.objects.filter(usuario=pedido.usuario)
    pedido_form.fields['endereco'].queryset = enderecos
    pedido_form.fields['telefone'].queryset = telefones
    
    fretes = [e.bairro.frete for e in enderecos]
    
    return render_to_response('confirmar_pedido.html', {'pedido': pedido, 
        'form': pedido_form, 'fretes': fretes}, 
        context_instance=RequestContext(request))


@login_required
@pedido_required
def cancelar_pedido(request):
	pedido = request.session[PEDIDO_SESSION_KEY]
	del request.session[PEDIDO_SESSION_KEY]
	pedido.delete()
	
	return redirect(reverse('index'))


@login_required
def acompanhar_pedido(request):
	pedidos = Pedido.objects.filter(usuario=request.user).exclude(status=Pedido.EM_ABERTO).order_by('-data')
	return render_to_response('acompanhar_pedido.html',{'pedidos': pedidos})

################################################################################


def cardapio(request):
	pizzas = Pizza.objects.all()
	itens = Item.objects.all()
	return render_to_response('cardapio.html',
	    {'pizzas' : pizzas, 'itens': itens},
	    context_instance=RequestContext(request))


def contato(request):
	teste = ['telefone','email','endereco']
	return render_to_response('contato.html',{'teste':teste})


def sobre(request):
	return render_to_response('sobre.html',{'historia':'alguma coisa'})
